<template>
  <div class="auto-token-status">
    <a-dropdown :trigger="['click']" placement="bottomRight">
      <a-button type="text" size="small" :loading="loading">
        <template #icon>
          <SyncOutlined v-if="autoRefreshEnabled" :spin="needsAutoRefresh" style="color: #1890ff" />
          <ClockCircleOutlined v-else />
        </template>
        <a-badge :status="getBadgeStatus()" :text="statusText" />
      </a-button>

      <template #overlay>
        <a-menu class="w-80">
          <a-menu-item disabled>
            <div class="p-3">
              <div class="flex items-center justify-between mb-2">
                <span class="text-sm font-medium">🤖 智能Token管理</span>
                <a-switch
                  v-model:checked="autoRefreshEnabled"
                  @change="toggleAutoRefresh"
                  size="small"
                  checked-children="自动"
                  un-checked-children="手动"
                />
              </div>

              <a-divider style="margin: 8px 0" />

              <div class="space-y-2">
                <div class="flex items-center justify-between">
                  <span class="text-xs text-gray-500">Token状态:</span>
                  <a-tag :color="statusColor" size="small">
                    {{ statusText }}
                  </a-tag>
                </div>

                <div class="flex items-center justify-between">
                  <span class="text-xs text-gray-500">剩余时间:</span>
                  <span class="text-xs font-medium" :class="getTimeColorClass()">
                    {{ remainingTimeText }}
                  </span>
                </div>

                <div class="flex items-center justify-between" v-if="tokenInfo">
                  <span class="text-xs text-gray-500">过期时间:</span>
                  <span class="text-xs text-gray-500">
                    {{ formatExpirationTime() }}
                  </span>
                </div>

                <div class="flex items-center justify-between">
                  <span class="text-xs text-gray-500">自动续期:</span>
                  <span class="text-xs" :class="autoRefreshEnabled ? 'text-green-500' : 'text-orange-500'">
                    {{ autoRefreshEnabled ? '✅ 已启用' : '⚠️ 已禁用' }}
                  </span>
                </div>

                <div class="flex items-center justify-between" v-if="needsAutoRefresh">
                  <span class="text-xs text-gray-500">续期状态:</span>
                  <span class="text-xs text-blue-500 flex items-center">
                    <SyncOutlined :spin="true" class="mr-1" />
                    准备续期中...
                  </span>
                </div>
              </div>
            </div>
          </a-menu-item>

          <a-menu-divider />

          <a-menu-item @click="handleManualRefresh" :disabled="loading">
            <template #icon>
              <ReloadOutlined :spin="loading" />
            </template>
            手动续期 (备用)
          </a-menu-item>

          <a-menu-item @click="handleCheckStatus" :disabled="loading">
            <template #icon>
              <CheckCircleOutlined />
            </template>
            检查状态
          </a-menu-item>

          <a-menu-divider />

          <a-menu-item disabled>
            <div class="text-xs text-gray-400 px-2">
              💡 自动模式下系统会智能检测并自动续期Token
            </div>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  ReloadOutlined,
  SyncOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import { useAutoTokenManager } from '#/hooks/useAutoTokenManager';

const {
  tokenInfo,
  loading,
  statusText,
  statusColor,
  remainingTimeText,
  autoRefreshEnabled,
  needsAutoRefresh,
  renewalThresholdMinutes,
  getTokenStatus,
  manualRefresh,
  toggleAutoRefresh,
} = useAutoTokenManager();

// 获取徽章状态
const getBadgeStatus = () => {
  if (!tokenInfo.value) return 'default';

  if (!tokenInfo.value.valid) return 'error';

  if (needsAutoRefresh.value) return 'processing';

  if (tokenInfo.value.remainingTimeMs < 5 * 60 * 1000) return 'error';

  return 'success';
};

// 获取时间颜色类名
const getTimeColorClass = () => {
  if (!tokenInfo.value) return 'text-gray-500';

  const remainingMs = tokenInfo.value.remainingTimeMs;
  const criticalThreshold = Math.min(renewalThresholdMinutes.value / 2, 5) * 60 * 1000;
  const warningThreshold = renewalThresholdMinutes.value * 60 * 1000;

  if (remainingMs < criticalThreshold) {
    return 'text-red-500 font-bold animate-pulse';
  } else if (remainingMs < warningThreshold) {
    return 'text-orange-500 font-medium';
  } else {
    return 'text-green-500';
  }
};

// 格式化过期时间
const formatExpirationTime = () => {
  if (!tokenInfo.value?.expirationTime) return '未知';

  const date = new Date(tokenInfo.value.expirationTime);
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

// 手动刷新Token
const handleManualRefresh = async () => {
  const success = await manualRefresh();
  if (success) {
    console.log('手动续期成功！自动模式将继续监控');
  }
};

// 检查Token状态
const handleCheckStatus = async () => {
  await getTokenStatus();
  console.log('Token状态已更新');
};
</script>

<style scoped>
.auto-token-status {
  position: relative;
}

.space-y-2 > * + * {
  margin-top: 0.5rem;
}

.text-xs {
  font-size: 0.75rem;
}

.text-sm {
  font-size: 0.875rem;
}

.text-gray-400 {
  color: #9ca3af;
}

.text-gray-500 {
  color: #6b7280;
}

.text-green-500 {
  color: #10b981;
}

.text-orange-500 {
  color: #f59e0b;
}

.text-red-500 {
  color: #ef4444;
}

.text-blue-500 {
  color: #3b82f6;
}

.font-medium {
  font-weight: 500;
}

.font-bold {
  font-weight: 700;
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: .5;
  }
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.mr-1 {
  margin-right: 0.25rem;
}

.mb-2 {
  margin-bottom: 0.5rem;
}

.p-3 {
  padding: 0.75rem;
}

.px-2 {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}
</style>
